package com.sam.im.heiqun.callmain;

import org.json.JSONObject;
import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;

import io.socket.client.Ack;

import static com.sam.im.heiqun.app.App.socket;

/**
 * Created by jack on 2017-07-15.
 */

public class RtcConnObserver implements PeerConnection.Observer {
    private RtcListener listener;
    public static String destid ;
    public RtcConnObserver(RtcListener listener){
        this.listener=listener;
    }

    @Override
    public void onSignalingChange(PeerConnection.SignalingState signalingState) {

    }

    @Override
    public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
        if(iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED) {
            //listener.onRemoveRemoteStream();
        }
    }

    @Override
    public void onIceConnectionReceivingChange(boolean b) {

    }

    @Override
    public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {

    }

    @Override
    public void onIceCandidate(IceCandidate iceCandidate) {
        try{
            JSONObject payload = new JSONObject();
            payload.put("sdpMLineIndex", iceCandidate.sdpMLineIndex);
            payload.put("sdpMid", iceCandidate.sdpMid);
            payload.put("candidate", iceCandidate.sdp);
            String content=payload.toString();
            // Log.i("info","=======RtcConnObserver");
            JSONObject msg=IMMessage.createSimpleMsg(content,49);
            socket.emit("chat", msg, new Ack() {
                @Override
                public void call(Object... args) {
                    System.out.println("ice sent.");
                }
            });
        }catch (Exception e){
            System.out.println("ice sent error");
        }

    }

    @Override
    public void onAddStream(MediaStream mediaStream) {
        listener.onAddRemoteStream(mediaStream);
    }

    @Override
    public void onRemoveStream(MediaStream mediaStream) {
        listener.onRemoveRemoteStream();
    }

    @Override
    public void onDataChannel(DataChannel dataChannel) {

    }

    @Override
    public void onRenegotiationNeeded() {

    }
}
